package com.shakespace.artofandroid.chapter05remoteview

import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.RemoteViews
import com.shakespace.artofandroid.R
import com.shakespace.firstlinecode.global.TAG

/**
 * Implementation of App Widget functionality.
 */
class NewAppWidget : AppWidgetProvider() {

    init {
        Log.e(this.TAG, "init----: ")
    }

    /**
     * 当点击时 ，触发action， onReceive调用，在AppWidgetProvider
     */
    override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
        Log.e(this.TAG, "onUpdate: ----")
        // There may be multiple widgets active, so update all of them
        for (appWidgetId in appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId)
        }
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        super.onReceive(context, intent)
        Log.e(this.TAG, "onReceive: -----  ${intent?.action}")
    }
    
    override fun onEnabled(context: Context) {
        Log.e(this.TAG, "onEnabled: ----")
        // Enter relevant functionality for when the first widget is created
    }

    override fun onDisabled(context: Context) {
        Log.e(this.TAG, "onDisabled: -----")
        // Enter relevant functionality for when the last widget is disabled
    }

    companion object {

        internal fun updateAppWidget(
            context: Context, appWidgetManager: AppWidgetManager,
            appWidgetId: Int
        ) {
            Log.e(this.TAG, "updateAppWidget: ------")
            val widgetText = context.getString(R.string.appwidget_text)
            // Construct the RemoteViews object
            val views = RemoteViews(context.packageName, R.layout.new_app_widget)
            views.setTextViewText(R.id.appwidget_text, widgetText)

//            views.setOnClickPendingIntent()
            // Instruct the widget manager to update the widget
            appWidgetManager.updateAppWidget(appWidgetId, views)

            //  可以在另一个应用注册一个广播，在这里将remoteview发送过去
            // 在另一个应用接收并显示 ， 可以实现远程更新
            //  适合更新频繁，布局简单的效果
            /**
             *   在不同应用，同一个资源名称对应的id值可能不一样，因此要接收的地方要用getIdentifier获取布局id
             *         val identifier = resources.getIdentifier("xxxxx", "layout", packageName)
             *              layoutInflater.inflate(identifier,parentView,false)
             */

//            val intent = Intent("custom_action")
//            intent.putExtra("remoteview",views)
//            context.sendBroadcast(intent)
        }
    }
}

